<template>
  <div class="form-container" :class="{ 'page-container': !inModal }">
    <page-form :model="form" ref="formRef" layout="vertical">
      <card title="车辆信息">
        <car-info-block :carInfo="carInfo" :fieldList="fieldList" />
      </card>

      <!-- 违章提醒 -->
      <a-alert class="mb-4" v-if="waitViolationFlag">
        您选择的车辆存在待处理的违章订单，年检前请尽快处理违章
        <a-link @click="toViewViolation">【立即去处理违章】</a-link>
      </a-alert>

      <card title="年检信息">
        <a-alert class="mb-4">
          年检证建议上传12123电子年检证。支持的格式：JPG、JPEG、PNG、WEBP。<a-link @click="exampleVisible = true">示例</a-link>，<a-link @click="openHelp"
            >电子年检证获取路径</a-link
          >
        </a-alert>
        <a-image-preview :src="exampleImg" v-model:visible="exampleVisible" />

        <page-form-row>
          <page-form-item field="inspectionFileId" label="上传年检证">
            <upload-ocr v-model="form.inspectionFileId" ocrType="inspection" @ocrClick="inspectionFileIdOCRSuccess" />
          </page-form-item>
        </page-form-row>
        <page-form-row>
          <page-form-item field="siteId" label="年检单关联门店" :rules="{ required: true, message: '请选择年检单关联门店' }">
            <remote-select v-model="form.siteId" :initStr="form.siteName" type="site_listBystaff" />
          </page-form-item>

          <page-form-item label="本次年检日期" field="inspectionTime">
            <i-date-picker class="w-full" v-model="form.inspectionTime" value-format="YYYY-MM-DD 00:00:00" @change="setPlanTime" />
          </page-form-item>

          <page-form-item
            field="inspectionLimitDay"
            label="年检间隔时间"
            labelTooltipContent="用于计算下次年检日期，年检有效期至=本次年检日期+年检间隔时间。"
          >
            <i-input-number v-model="form.inspectionLimitDay" unit="天" precision="0" max="9999" @change="setPlanTime" />
          </page-form-item>
          <page-form-item label="年检有效期至" field="planTime">
            <i-date-picker class="w-full" v-model="form.planTime" value-format="YYYY-MM-DD" />
          </page-form-item>

          <page-form-item field="locationId" label="年检厂">
            <template #label-extra>
              <i-add-supplier typeText="年检" supplierType="6" @addOk="addSupplierOk" />
            </template>
            <remote-select
              v-model="form.locationId"
              type="supplier_list"
              :params="{
                supplierType: 6,
                idList: form.locationId ? [form.locationId] : undefined,
                status: 1,
              }"
            />
          </page-form-item>

          <page-form-item label="承租人信息">
            <remote-select
              :disabled="pageParams.byOrder"
              v-model="form.memberId"
              :params="{
                oldId: form.memberId,
                carId: form.carId,
                orderTypeList: [3],
              }"
              type="member_list_label"
              @change="changeMemberFn"
            />
          </page-form-item>
          <page-form-item label="关联订单号">
            <template #label-extra>
              <span class="text-jcr"> 交车人：{{ form.giveStaffName || '-' }} </span>
            </template>
            <a-select
              v-model="form.businessOrderId"
              :disabled="pageParams.byOrder"
              placeholder="请选择"
              allow-clear
              allow-search
              @change="changeOrderIdFn"
              popup-container=".form-container"
            >
              <a-option v-for="item in longOrderIdList" :key="item.orderId" :value="item.orderId" :label="item.label">
                {{ item.label }}
              </a-option>
            </a-select>
          </page-form-item>

          <page-form-item field="undertakerId" label="负责人">
            <remote-select
              v-model="form.undertakerId"
              type="staff_authOrg"
              @change="changeUndertakerIdFn"
              :params="{ oldId: form.undertakerId, siteIdList: [carInfo.siteId] }"
            />
          </page-form-item>

          <page-form-item label="备注" size="2/3">
            <i-input textarea v-model="form.remark" />
          </page-form-item>
        </page-form-row>
        <page-form-row>
          <page-form-item label="上传照片" field="fileIdList" style="margin-bottom: -6px" size="1">
            <upload-img v-model="form.fileIdList" limit="30" />
          </page-form-item>
        </page-form-row>
      </card>
      <card title="年检费用" :showDivider="false">
        <page-form-row>
          <page-form-item field="inspectionAmount" label="年检费">
            <template #label-extra v-if="assetFeeInfo.feeStatus == 1">
              <a-tag color="orangered">
                <template #icon>
                  <icon-exclamation-circle-fill />
                </template>
                已付款无法编辑
              </a-tag>
            </template>
            <i-input-number v-model="form.inspectionAmount" unit="元" :disabled="assetFeeInfo.feeStatus == 1" />
          </page-form-item>
          <page-form-item label="费用备注" size="2/3">
            <i-input textarea v-model="form.feeRemark" />
          </page-form-item>
        </page-form-row>
      </card>
    </page-form>
  </div>
  <page-form-footer @ok="submitFn" :ok-loading="okLoading" v-if="inModal == false" />
</template>

<script setup name="CarInspectForm">
  import dayjs from 'dayjs'
  import { ref, provide, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import useNavigate from '@/hooks/useNavigate'
  import useUserStore from '@/store/modules/user'
  import exampleImg from '@/assets/help/example_AS.png'
  import { Modal, Message } from '@arco-design/web-vue'
  import { addInspect, getCarViolationInfo, inspectDetail, getCarDetail, getOrderCarInfo } from '@/api/asset/carInspect'
  import { getRelationOrderNo } from '@/api/asset/maintenance'
  import { ruleDetail } from '@/api/system/backlogrule'

  const props = defineProps({
    inModal: Boolean,
    params: Object,
  })

  const exampleVisible = ref(false)
  const route = useRoute()
  const userStore = useUserStore()
  userStore.setEpDetail()
  const { navigateBack, navigateTo } = useNavigate()

  // 计算下次年检日期
  const setPlanTime = () => {
    if (form.value.inspectionTime && form.value.inspectionLimitDay != undefined) {
      form.value.planTime = dayjs(form.value.inspectionTime).add(form.value.inspectionLimitDay, 'day').format('YYYY-MM-DD')
    }
  }

  const carInfo = ref({})
  const form = ref({})
  // 初始化参数
  const pageParams = ref({})
  const initPageParams = () => {
    if (props.inModal) {
      // 车辆详情（新增&编辑）
      pageParams.value = { ...props.params }
    } else {
      // 车辆列表&长租（新增）
      if (route.query.page == 'longOrder') {
        pageParams.value = {
          orderId: route.params.id,
          page: 'longOrder',
          byOrder: true,
        }
      } else {
        pageParams.value = {
          carId: route.params.id,
          page: 'carList',
        }
      }
    }
  }

  const assetFeeInfo = ref({})
  const getInterceptDetail = () => {
    inspectDetail({ id: pageParams.value.id }).then((res) => {
      if (res.code == 200) {
        carInfo.value = res.result
        assetFeeInfo.value = res.result.assetFeeInfo || {}
        form.value = {
          // 年检基本信息
          id: res.result.id,
          carId: res.result.carId,
          licenseNo: res.result.licenseNo,
          siteId: res.result.siteId,
          siteName: res.result.siteName,
          planTime: res.result.planTime,
          locationId: res.result.locationId,
          inspectionTime: res.result.inspectionTime,
          inspectionFileId: res.result.inspectionFileId,
          // 承租人
          memberId: res.result.memberId,
          memberName: res.result.memberName,
          memberPhone: res.result.memberPhone,
          // 关联订单
          businessOrderId: res.result.businessOrderId,
          orderNo: res.result.orderNo,
          orderType: res.result.orderType,
          // 负责人
          undertakerId: res.result.undertakerId,
          undertaker: res.result.undertaker,
          remark: res.result.remark,
          fileIdList: res.result.fileIdList,
          // 年检费用
          inspectionAmount: res.result.inspectionAmount,
          feeRemark: res.result.feeRemark,
          // 年检间隔时间（代办事项配置，不参与保存）
          inspectionLimitDay: inspectionLimitDay.value,
        }
        getOrderNumber()
        // 获取违章
        getCarViolationInfoApi()
      }
    })
  }

  const getCarInfoDetail = () => {
    getCarDetail({ id: pageParams.value.carId }).then((res) => {
      if (res.code == 200) {
        carInfo.value = res.result
        form.value = {
          carId: res.result.id,
          licenseNo: res.result.licenseNo,
          siteId: res.result.siteId,
          siteName: res.result.siteName,
          // 负责人默认登录人
          undertakerId: userStore.employeeId,
          undertaker: userStore.realName,
          // 年检间隔时间（代办事项配置，不参与保存）
          inspectionLimitDay: inspectionLimitDay.value,
        }
        getOrderNumber(true) //查关联订单号列表
        // 获取违章
        getCarViolationInfoApi()
      }
    })
  }

  const getOrderDetail = () => {
    getOrderCarInfo({ id: pageParams.value.orderId, type: 3 }).then((res) => {
      if (res.code == 200) {
        carInfo.value = res.result
        form.value = {
          carId: res.result.carId,
          licenseNo: res.result.licenseNo,
          // 订单信息
          businessOrderId: res.result.orderId,
          orderNo: res.result.orderCode,
          orderType: 3, // 长租
          giveStaffName: res.result.giveStaffName,
          giveStaffId: res.result.giveStaffId,
          siteId: res.result.siteId,
          siteName: res.result.siteName,
          memberId: res.result.memberId,
          memberName: res.result.memberName,
          memberPhone: res.result.mememberPhone,
          // 负责人默认登录人
          undertakerId: userStore.employeeId,
          undertaker: userStore.realName,
          // 年检间隔时间（代办事项配置，不参与保存）
          inspectionLimitDay: inspectionLimitDay.value,
        }
        longOrderIdList.value = [
          {
            label: res.result.orderCode,
            orderNo: res.result.orderCode,
            value: res.result.orderId,
            orderId: res.result.orderId,
          },
        ]
        // 获取违章
        getCarViolationInfoApi()
      }
    })
  }

  // 初始化年检间隔时间
  const inspectionLimitDay = ref(undefined)
  const initInspectionLimitDay = () => {
    return new Promise((resolve) => {
      ruleDetail()
        .then((res) => {
          inspectionLimitDay.value = res.result.inspectionLimitDay
        })
        .finally(() => {
          resolve()
        })
    })
  }

  const fieldList = ref([
    { label: '车架号', prop: 'vin' },
    { label: '车辆当前归属门店', prop: 'siteName' },
    { label: '归属车场', prop: 'libraryName' },
    { label: '年检单号', prop: 'inspectionNo' },
  ])
  onMounted(async () => {
    // 初始化参数
    initPageParams()
    await initInspectionLimitDay()
    // 编辑
    if (pageParams.value.id) {
      getInterceptDetail()
      fieldList.value[1].prop = 'carSiteName'
      return
    }
    // 新增不展示年检单号
    fieldList.value = fieldList.value.splice(0, 3)
    // 从订单新增
    if (pageParams.value.orderId) {
      getOrderDetail()
    }
    // 从车辆新增
    if (pageParams.value.carId) {
      getCarInfoDetail()
    }
  })

  // 清空订单相关信息
  const clearOrderInfo = () => {
    form.value.businessOrderId = null
    form.value.orderNo = null
    form.value.orderType = null
    form.value.giveStaffName = null
  }
  // 选择订单
  const changeOrderIdFn = (value) => {
    if (value) {
      longOrderIdList.value.map((item) => {
        if (item.orderId === value) {
          form.value.businessOrderId = item.orderId
          form.value.orderNo = item.orderNo
          form.value.orderType = item.orderType
          // 承租人信息
          form.value.memberId = item.memberId
          form.value.memberPhone = item.memberPhone
          form.value.memberName = item.memberName
          form.value.giveStaffName = item.giveStaffName
        }
      })
    } else {
      clearOrderInfo()
    }
  }

  // 获取长租订单
  const longOrderIdList = ref([])
  const getOrderNumber = (defaultSelectFirst = false) => {
    const orderId = form.value.businessOrderId
    getRelationOrderNo({
      carId: form.value.carId,
      orderTypeList: [3],
      memberId: form.value.memberId,
      useAuth: 1,
      oldOrderType: form.value.orderType,
      oldOrderId: orderId,
    }).then((res) => {
      if (res.result?.length > 0) {
        res.result.forEach((item) => {
          item.label = '【' + item.orderTypeStr + '】' + item.orderNo
          item.value = item.orderId
        })
        longOrderIdList.value = res.result
      } else {
        longOrderIdList.value = []
        clearOrderInfo()
      }
      // 处理默认选中逻辑
      if (longOrderIdList.value?.length > 0) {
        // 当前存在已选择的订单时，判断是否存在于当前的列表中，如存在，则不再重新给与默认值
        if (orderId) {
          const hasSameOrderId = longOrderIdList.value.some((item) => item.orderId == orderId)
          if (hasSameOrderId) {
            // 存在相同订单，则不再默认选中第一个
            defaultSelectFirst = false
          }
        }
        // 默认选中第一个
        if (defaultSelectFirst) {
          form.value.businessOrderId = longOrderIdList.value[0].orderId //默认第一个
          form.value.orderNo = longOrderIdList.value[0].orderNo
          form.value.giveStaffId = longOrderIdList.value[0].giveStaffId //默认第一个
          form.value.orderType = longOrderIdList.value[0].orderType
          form.value.giveStaffName = longOrderIdList.value[0].giveStaffName
          // 如果当前不存在承租人
          if (!form.value.memberId) {
            // 承租人
            form.value.memberId = longOrderIdList.value[0].memberId
            // 重新获取关联订单号列表
            getOrderNumber(defaultSelectFirst)
          }
        }
      }
    })
  }

  // 获取车辆违章信息
  const waitViolationFlag = ref(false)
  const getCarViolationInfoApi = () => {
    let params = {
      pageNumber: 1,
      pageSize: 10,
      carId: form.value.carId,
      eventStatus: 0,
    }
    getCarViolationInfo(params).then((res) => {
      if (res.code == 200) {
        console.log(res)
        if (res.result.data.length) {
          waitViolationFlag.value = true
        }
      }
    })
  }

  // 跳转违章列表
  const toViewViolation = () => {
    if (form.value.licenseNo) {
      let data = form.value.licenseNo
      navigateTo(`/assets/violation/car-violation?licenseNo=${data}&source=inpect`)
    }
  }

  // 更换承租人
  const changeMemberFn = (value) => {
    let defaultSelectFirst = false
    if (value) {
      defaultSelectFirst = true
    }
    getOrderNumber(defaultSelectFirst)
  }

  // 选择 负责人
  const changeUndertakerIdFn = (_, option = {}) => {
    form.value.undertaker = option.realname
  }

  // 获取子组件的数据
  const addSupplierOk = (id) => {
    form.value.locationId = id
  }

  provide('form', form)
  const formRef = ref()
  const okLoading = ref(false)
  const submitFn = (noticeSuccess, validateInspect = true) => {
    formRef.value.validate((error) => {
      if (!error) {
        // 校验年检时间
        if (validateInspect && validateInspectTimeFn(noticeSuccess) == false) {
          if (props.inModal) {
            // noticeSuccess 此方法是弹框传入的方法，包含成功提示和关闭窗口
            noticeSuccess(false)
          }
          return
        }
        const param = {
          ...form.value,
        }
        okLoading.value = true
        addInspect(param)
          .then(() => {
            if (props.inModal) {
              // noticeSuccess 此方法是弹框传入的方法，包含成功提示和关闭窗口
              noticeSuccess()
              return
            }
            noticeSuccess()
            navigateBack()
          })
          .finally(() => {
            if (props.inModal) {
              // noticeSuccess 此方法是弹框传入的方法，包含成功提示和关闭窗口
              noticeSuccess(false)
              return
            }
            okLoading.value = false
          })
      } else {
        if (props.inModal) {
          // noticeSuccess 此方法是弹框传入的方法，包含成功提示和关闭窗口
          noticeSuccess(false)
          return
        }
      }
    })
  }

  // 校验年检时间，给出提示
  const validateInspectTimeFn = (noticeSuccess) => {
    // 编辑不校验
    if (form.value.id) return true
    const tip = '新增年检的有效期早于车辆上的年检有效期，请确认是否新增？'

    // 获取当前车辆的下次年检日期
    const currentPlanTime = carInfo.value.planTime
    // 获取新增的年检日期
    const newPlanTime = form.value.planTime

    // 检查日期是否有效
    if (currentPlanTime && newPlanTime) {
      const currentPlanDate = dayjs(currentPlanTime)
      const newPlanDate = dayjs(newPlanTime)

      // 比较日期
      if (newPlanDate.isBefore(currentPlanDate)) {
        // 提示用户
        Modal.confirm({
          title: '提示',
          simple: true,
          content: tip,
          onOk: () => {
            submitFn(noticeSuccess, false)
          },
        })
        return false
      }
    }

    // 如果日期合理或未设置日期，则返回 true
    return true
  }

  // 查看帮助
  const openHelp = () => {
    window.open('https://image.qichengcx.com/svms/ccms/guide.pdf?#', '_blank')
  }

  // ocr成功回调
  const inspectionFileIdOCRSuccess = (res) => {
    if (res?.date) {
      Message.success('读取成功')
      form.value.planTime = res.date
    }
  }

  defineExpose({
    submitFn,
    form,
  })
</script>

<style lang="less" scoped>
  .form-container {
    position: relative;
    width: 100%;
    overflow: hidden;
  }
  .text-jcr {
    color: #1890ff;
  }
</style>
